package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.search.dtos.UserSearchDto;
import com.usian.model.search.pojos.ApAssociateWords;
import com.usian.search.mapper.ApAssociateWordsMapper;
import com.usian.search.model.Trie;
import com.usian.search.service.ApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author zlm
 * @version 1.0
 * @date 2022/9/29 11:30
 */
@Service
public class ApAssociateWordsServiceImpl extends ServiceImpl<ApAssociateWordsMapper, ApAssociateWords> implements ApAssociateWordsService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //匹配搜索联想词
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        Page<ApAssociateWords> wordsPage = new Page<>(userSearchDto.getPageNum(), userSearchDto.getPageSize());
        IPage<ApAssociateWords> iPage = page(wordsPage, Wrappers.<ApAssociateWords>lambdaQuery().like(ApAssociateWords::getAssociateWords, userSearchDto.getSearchWords()));
        return ResponseResult.okResult(iPage.getRecords());
    }

    @Override
    public ResponseResult searchv2(UserSearchDto userSearchDto) {
        String redisCache = redisTemplate.boundValueOps("associate_list").get();
        List<ApAssociateWords> apAssociateWords = null;
        if (StringUtils.isNotEmpty(redisCache)){
            apAssociateWords = JSON.parseArray(redisCache,ApAssociateWords.class);
        }else {
            apAssociateWords = list();
            redisTemplate.boundValueOps("associate_list").set(JSON.toJSONString(apAssociateWords));
        }
        Trie t = new Trie();
        for (ApAssociateWords apAssociateWord : apAssociateWords) {
            t.insert(apAssociateWord.getAssociateWords());
        }
        List<String> ret = t.startWith(userSearchDto.getSearchWords());

        return ResponseResult.okResult(ret);
    }
}
